package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepsitory;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepsitory strategyThemeRepsitory;

    @Autowired
    private MongoTemplate template;


    //容易让mongodb产生误会,后续自动生成的id不会存进去
    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemeRepsitory.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        strategyThemeRepsitory.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemeRepsitory.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemeRepsitory.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return strategyThemeRepsitory.findAll();
    }

    //页面数据
    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(),
                                Sort.Direction.ASC,"_id");
        return DBHelper.query(query,StrategyTheme.class,template,pageable);
    }

    //保存或修改
    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (!StringUtils.hasLength(strategyTheme.getId())){
            this.save(strategyTheme);
        }else {
            this.update(strategyTheme);
        }
    }

}
